<template>
  <div>
    <el-form>
      <el-select v-if="type === 'select'" v-model="model" :disabled="disabled" clearable filterable @change="change">
        <el-option value="title" :disabled="true">
          <span class="option-span-short">代码</span>
          <span class="option-span-short">名称</span>
        </el-option>
        <el-option v-for="(item,index) in select" :key="index" :label="item.name" :value="item.code">
          <span class="option-span-short">{{ item.code }}</span>
          <span class="option-span-short">{{ item.name }}</span>
        </el-option>
      </el-select>
      <span v-if="type === 'span'">{{ find(select,model,'name','code') }}</span>
    </el-form>
  </div>
</template>

<script>
import scode from '@/api/modules/basic-code/s-code/index'
export default {
  props: {
    code: {
      type: String,
      default: '',
    },
    flgEng: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: 'select',
    },
  },
  data() {
    return {
      model: '',
      select: [],
    }
  },
  methods: {
    /*
     *  查询基础代码
     */
    async queryScode(flgEng){
      if(sessionStorage.getItem(flgEng) == null){
        const params = {fldEng:flgEng}
        const res = await scode.queryScode(params)
        if (res.code === '00000000') {
          this['select'] = res.data
          sessionStorage.setItem(flgEng, JSON.stringify(res.data))
        }
      }else{
        this['select'] = JSON.parse(sessionStorage.getItem(flgEng))
      }
    },
    /*
     *  选中值发生变化
     */
    change(value){
      this.$emit('update:code',value)
    },
    /*
     *  对象数组检索
     */
    find(arr,str,key,value) {
      let res = str
      for( let i of arr){
        if(i[value] === str){
          res = i[key]
        }
      }
      return res
    },
  },
  mounted() {
  	this.queryScode(this.flgEng)
    this.model = this.code
  },
  watch:{
    code(news,olds){
      this.model = news
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

.option-span-short {
  display: inline-block;
  padding-right: 5px;
  width: 50px;
  text-align: center;
}

</style>
